<template>
	<view class="container">
		<!-- 内容区域 -->
		<scroll-view class="content-scroll" scroll-y>
			<!-- 酒店基础信息卡片 -->
			<view class="card hotel-info-card">
				<view class="hotel-name">{{ hotelName }}</view>
				<view class="hotel-address">
					<uni-icons type="location" size="16" color="#666"></uni-icons>
					<text>{{ hotelAddress }}</text>
				</view>
				<view class="date-picker" @click="showCalendar=!showCalendar">
					<view class="date-info">
						<view class="date-range">
							<text class="date">{{ formatDate(checkInDate) }}</text>
							<text class="separator">-</text>
							<text class="date">{{ formatDate(checkOutDate) }}</text>
						</view>
						<text class="nights">共{{ nightNum }}晚</text>
					</view>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
				<view class="room-info">
					<image class="room-image"
						src="https://public.readdy.ai/ai/img_res/4fc142054abd14860465774aa1d719a9.jpg"
						mode="aspectFill"></image>
					<view class="room-detail">
						<view class="room-name">{{ roomName }}</view>
						<view class="room-tags">
							<text class="tag">单人入住</text>
							<text class="tag">含早餐</text>
						</view>
						<view class="cancel-rule">
							<uni-icons type="info" size="14" color="#FF6000"></uni-icons>
							<text>18:00前可免费取消</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 预订详情卡片 -->
			<view class="card booking-detail-card">
				<view class="card-title">预订信息</view>
				<view class="room-count">
					<view class="count-label">房间数量</view>
					<view class="count-control">
						<view class="count-btn minus" @click="decreaseRoomCount">
							<text>-</text>
						</view>
						<text class="count-value">{{ roomCount }}</text>
						<view class="count-btn plus" @click="increaseRoomCount">
							<text>+</text>
						</view>
					</view>
					<text class="count-tip">每间最多住2人</text>
				</view>
				<view class="divider"></view>
				<view class="contact-info">
					<view class="input-item">
						<text class="input-label">入住人</text>
						<input type="text" v-model="contactName" placeholder="请填写入住人姓名"
							placeholder-class="placeholder" />
					</view>
					<view class="input-item">
						<text class="input-label">手机号</text>
						<input type="number" v-model="contactPhone" placeholder="请填写手机号码"
							placeholder-class="placeholder" />
					</view>
					<view class="input-item">
						<text class="input-label">备注</text>
						<textarea v-model="remark" placeholder="如有特殊需求请在此说明" placeholder-class="placeholder"
							class="remark-input"></textarea>
					</view>
				</view>
			</view>

			<!-- 底部占位，确保内容不被底部操作栏遮挡 -->
			<view class="bottom-placeholder"></view>
		</scroll-view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="price-info">
				<text class="price-label">总价：</text>
				<text class="price-symbol">¥</text>
				<text class="price-value">{{ totalPrice.toFixed(2) }}</text>
			</view>
			<button class="submit-btn" @click="submitOrder">提交订单</button>
		</view>

		<!-- 日期选择弹窗 -->
		<u-calendar :show="showCalendar" :mouthType="mouthType" mode="range" @close="showCalendar = false"
			@confirm="handleDateConfirm"></u-calendar>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed } from 'vue';
	import {
		onUnload,
		onLoad,
		onHide
	} from "@dcloudio/uni-app";
	// import DatePicker from '@/components/date-picker/date-picker.vue';
	import { orderCreate, oaLogin, boolonOrderCheck, get_price, deposit_orderCreate, payDeposit, deposit_orderCancel, payLKLPay } from '@/utils/apiPost.js'
	import { getToken } from '@/utils/token.js'
	import { calculateNights } from '@/utils/time.js'
	import WechatSDK from '@/utils/wechat_sdk.js';
	import wx from 'weixin-js-sdk';
	// 接收页面参数
	const roomId = ref('');
	const roomName = ref('纯享单人间'); // 默认值
	const basePrice = ref(245); // 默认值
	const hotelName = ref('庭酒店（杭州阿里店）'); // 默认值
	const hotelAddress = ref('杭州市余杭区文一西路969号'); // 默认值
	const showCalendar = ref(false); // 默认值
	

	onLoad((options) => {
		if (options.roomId) {
			roomId.value = options.roomId;
		}
		if (options.roomName) {
			roomName.value = options.roomName;
		}
		if (options.price) {
			basePrice.value = Number(options.price);
		}
		if (options.hotelName) {
			hotelName.value = decodeURIComponent(options.hotelName);
		}
		if (options.hotelAddress) {
			hotelAddress.value = decodeURIComponent(options.hotelAddress);
		}
		if (options.checkInDate) {
			checkInDate.value = options.checkInDate;
		}
		if (options.checkOutDate) {
			checkOutDate.value = options.checkOutDate;
		}
		if (options.mouthType) {
			mouthType.value = options.mouthType;
		}
		
		nightNum.value = calculateNights(checkInDate.value, checkOutDate.value)
		get_priceFun()
	});
	const get_priceFun = () => {
		let obj = {
			room_id: roomId.value,
			start_date: checkInDate.value,
			end_date: checkOutDate.value,
			number: roomCount.value
		}
		get_price(obj).then(res=>{
			console.log(res)
		}).catch(error=>{
			console.log(error)
		})
	}
	const roomPriceInfo = ref({
		
	})
	const nightNum = ref(1)
	// 日期相关
	const today = new Date();
	const checkInDate = ref(today.toISOString().split('T')[0]);
	const tomorrow = new Date(today);
	tomorrow.setDate(tomorrow.getDate() + 1);
	const checkOutDate = ref(tomorrow.toISOString().split('T')[0]);
	const mouthType = ref(0);

	// 计算入住天数
	const stayNights = computed(() => {
		const start = new Date(checkInDate.value);
		const end = new Date(checkOutDate.value);
		return Math.round((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
	});

	// 格式化日期
	const formatDate = (dateStr : string) => {
		const date = new Date(dateStr);
		const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
		const weekday = weekdays[date.getDay()];
		return `${date.getMonth() + 1}月${date.getDate()}日 ${weekday}`;
	};
	// 格式化日期
	// 格式化日期为 yyyy-MM-dd
	const formatDateStr = (dateStr : string) => {
		const date = new Date(dateStr);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		return `${year}-${month}-${day}`;
	}
	
	const handleDateConfirm = (e) => {
		console.log(e);
		showCalendar.value = false
		checkInDate.value = e[0]
		checkOutDate.value = e[e.length - 1]
	}
	// 房间数量
	const roomCount = ref(1);
	const increaseRoomCount = () => {
		if (roomCount.value < 5) {
			roomCount.value++;
		}
	};
	const decreaseRoomCount = () => {
		if (roomCount.value > 1) {
			roomCount.value--;
		}
	};

	// 联系人信息
	const contactName = ref('');
	const contactPhone = ref('');
	const remark = ref('');

	// 优惠券选择
	const selectCoupon = () => {
		uni.showToast({
			title: '暂无可用优惠券',
			icon: 'none'
		});
	};

	// 计算总价
	const totalPrice = computed(() => {
		let price = basePrice.value * roomCount.value;

		return price;
	});
	
	// 支付功能
	// 支付状态控制
	// const isPaying = ref(false);
	// const currentOrderId = ref(''); // 添加订单ID响应式变量
	// let popStateListener = null;
	
	// // 修复1：正确定义 preventScroll 方法
	// const preventScroll = (e) => {
	//   if (isPaying.value) {
	//     e.preventDefault();
	//     e.stopPropagation();
	//   }
	// };
	
	// // 支付完成后的统一处理
	// const finishPayment = () => {
	//   // 1. 恢复页面滚动（修复2：使用Uniapp API）
	//   // uni.pageScrollTo({
	//   //   scrollTop: 0,
	//   //   duration: 0
	//   // });
	//   document.body.removeEventListener('touchmove', preventScroll);
	  
	//   // 2. 清理返回拦截
	//   if (popStateListener) {
	//     window.removeEventListener('popstate', popStateListener);
	//   }
	//   history.replaceState(null, '', window.location.href.split('#')[0]);
	  
	//   // 3. 关闭加载状态
	//   uni.hideLoading();
	//   // 6. 重置支付状态
	//   isPaying.value = false;
	// };

	// // 支付失败回调
	// const handlePaymentFailure = (err) => {
	//   finishPayment();
	//   setTimeout(() => {
	// 	uni.showModal({
	// 	  title: '提示',
	// 	  content: `支付失败: ${err.errMsg || '未知错误'}`,
	// 	  showCancel: false
	// 	});
	//   }, 100);
	// };
	// // 支付成功回调
	// const handlePaymentSuccess = () => {
	// 	finishPayment();
	// 	setTimeout(() => {
	// 		uni.showToast({
	// 			title: '支付成功',
	// 			icon: 'none',
	// 			duration: 2000
	// 		});
	// 	}, 100);
	// };
	// 提交订单
	const submitOrder = () => {
		// uni.showToast({
		// 	title: '我点击了~',
		// 	duration: 1000
		// })
		if (!contactName.value) {
			uni.showToast({
				title: '请填写入住人姓名',
				icon: 'none'
			});
			return;
		}

		if (!contactPhone.value) {
			uni.showToast({
				title: '请填写手机号码',
				icon: 'none'
			});
			return;
		}
		
		
		// 普通房不用在这里判断是否有押金，直接下单并支付
		// 特价房需要判断是否有押金，有押金，进行支付，没有押金，
		
		
		if(mouthType.value == 2){  
			let params = {
				type: mouthType.value,
				day: nightNum.value
			}
			boolonOrderCheck(params).then(res=>{
				console.log('====================',res)
				// if(res.code == 1){
					// get_priceFun()
				// }
				if(res.code == 1){
					if(res.data.check_status == 0){
						uni.showModal({
							title: '提示',
							content: `押金不够，需要支付${res.data.diff_price}元押金`,
							confirmText: '支付',
							success: function (resModal) {
								if (resModal.confirm) {
									console.log('用户点击确定');
									let depositObj = {
										type: mouthType.value,
										day: nightNum.value
									}
									deposit_orderCreate(depositObj).then(depositRes=>{
										console.log(depositRes)
										if(depositRes.code == 1){
											let payObj = {
												order_id: depositRes.data.id
											}
											payDeposit(payObj).then(payRes=>{
												console.log(payRes)
												if(payRes.code == 1){
													uni.showLoading({
														title: '加载中……',
														mask: true
													})
													
													wx.config({
													  debug: false,
													  appId: payRes.data.appId,
													  timestamp: payRes.data.timeStamp || "",
													  nonceStr: payRes.data.nonceStr || "",
													  signature: payRes.data.paySign || "",
													  jsApiList: [
													    'chooseWXPay',         // 微信支付
													    'updateAppMessageShareData', // 分享到朋友圈
													    'updateTimelineShareData',    // 分享给朋友
														'getLocation', // 获取位置
															  // 其他需要调用的API
													  ]
													});
													wx.ready(() => {
														uni.hideLoading()
														wx.chooseWXPay({
														  timestamp: payRes.data.timeStamp,
														  nonceStr: payRes.data.nonceStr,
														  package: payRes.data.package,
														  signType: payRes.data.signType,
														  paySign: payRes.data.paySign,
														  success: (WXPayres) => {
															  console.log('支付成功')
															  uni.showToast({
																title: `支付成功${JSON.stringify(WXPayres)}`,
																duration: 1000,
																mask: true
															  })
														  },
														  fail: (WXPayerror) => {
															  uni.showToast({
																title: `支付失败${JSON.stringify(WXPayerror)}`,
																duration: 1000,
																mask: true
															  })
														  }
														});
													});
												}
											}).catch(payError=>{
												console.log(payError)
											})
										}
									}).catch(depositError=>{
										console.log(depositError)
									})
								} else if (resModal.cancel) {
									console.log('用户点击取消');
								}
							},
						})
					}else{
						let obj = {
							start_date: formatDateStr(checkInDate.value),
							end_date: formatDateStr(checkOutDate.value),
							room_id: Number(roomId.value),
							number: Number(roomCount.value),
							name: contactName.value,
							phone: contactPhone.value,
						}
						console.log(obj)
						orderCreate(obj).then(res=>{
							console.log(res)
							if(res.code == 1){
								uni.hideLoading();
								uni.showToast({
									title: '订单提交成功',
									icon: 'success',
									duration: 2000,
									mask: true,
									success: () => {
										setTimeout(() => {
											// uni.switchTab({
											// 	url: '/pages/order-list/order-list'
											// });
											if(res.code == 1){
												let payObj = {
													order_id: res.data.id
												}
												payLKLPay(payObj).then(payRes=>{
													console.log(payRes)
													if(payRes.code == 1){
														uni.showLoading({
															title: '加载中……',
															mask: true
														})
														
														wx.config({
														  debug: false,
														  appId: payRes.data.appId,
														  timestamp: payRes.data.timeStamp || "",
														  nonceStr: payRes.data.nonceStr || "",
														  signature: payRes.data.paySign || "",
														  jsApiList: [
														    'chooseWXPay',         // 微信支付
														    'updateAppMessageShareData', // 分享到朋友圈
														    'updateTimelineShareData',    // 分享给朋友
															'getLocation', // 获取位置
																  // 其他需要调用的API
														  ]
														});
														wx.ready(() => {
															uni.hideLoading()
															wx.chooseWXPay({
															  timestamp: payRes.data.timeStamp,
															  nonceStr: payRes.data.nonceStr,
															  package: payRes.data.package,
															  signType: payRes.data.signType,
															  paySign: payRes.data.paySign,
															  success: (WXPayres) => {
																  console.log('支付成功')
																  uni.showToast({
																  	title: `支付成功${JSON.stringify(WXPayres)}`,
																	duration: 1000,
																	mask: true
																  })
															  },
															  fail: (WXPayerror) => {
																  uni.showToast({
																  	title: `支付失败${JSON.stringify(WXPayerror)}`,
																	duration: 1000,
																	mask: true
																  })
															  }
															});
														});
													}
												}).catch(payError=>{
													console.log(payError)
												})
											}
										}, 2000);
									}
								});
							}
						}).catch(error=>{
							console.log(error)
						})
					}
				}
			}).catch(error=>{
				console.log(error)
			})
		}else{
			let obj = {
				start_date: formatDateStr(checkInDate.value),
				end_date: formatDateStr(checkOutDate.value),
				room_id: Number(roomId.value),
				number: Number(roomCount.value),
				name: contactName.value,
				phone: contactPhone.value,
			}
			console.log(obj)
			orderCreate(obj).then(res=>{
				console.log(res)
				if(res.code == 1){
					uni.hideLoading();
					if(res.code == 1){
						let payObj = {
							order_id: res.data.id
						}
						payLKLPay(payObj).then(payRes=>{
							console.log(payRes)
							if(payRes.code == 1){
								uni.showLoading({
									title: '加载中……',
									mask: true,
								})
								
								wx.config({
								  debug: false,
								  appId: payRes.data.appId,
								  timestamp: payRes.data.timeStamp || "",
								  nonceStr: payRes.data.nonceStr || "",
								  signature: payRes.data.paySign || "",
								  jsApiList: [
								    'chooseWXPay',         // 微信支付
								    'updateAppMessageShareData', // 分享到朋友圈
								    'updateTimelineShareData',    // 分享给朋友
									'getLocation', // 获取位置
										  // 其他需要调用的API
								  ]
								});
								wx.ready(() => {
									uni.hideLoading()
									wx.chooseWXPay({
									  timestamp: payRes.data.timeStamp,
									  nonceStr: payRes.data.nonceStr,
									  package: payRes.data.package,
									  signType: payRes.data.signType,
									  paySign: payRes.data.paySign,
									  // success: handlePaymentSuccess,
									  // fail: handlePaymentFailure
									  success: (WXPayres) => {
										  console.log('支付成功')
										  uni.showToast({
										  	title: `支付成功${JSON.stringify(WXPayres)}`,
											duration: 1000,
											mask: true
										  })
									  },
									  fail: (WXPayerror) => {
										  uni.showToast({
										  	title: `支付失败${JSON.stringify(WXPayerror)}`,
											duration: 1000,
											mask: true
										  })
									  }
									});
								});
							}
						}).catch(payError=>{
							console.log(payError)
						})
					}
					// uni.showToast({
					// 	title: '订单提交成功',
					// 	icon: 'success',
					// 	duration: 2000,
					// 	mask: true,
					// 	success: () => {
					// 		setTimeout(() => {// 4. 拦截返回操作
					// 			// 1. 初始化支付环境
					// 			// isPaying.value = true;
					// 			// document.body.style.overflow = 'hidden';
					// 			// document.body.addEventListener('touchmove', preventScroll, {
					// 			// 	passive: false
					// 			// });
					// 			// history.pushState(null, null, document.URL);
					// 			// popStateListener = (e) => {
					// 			// 	e.preventDefault();
					// 			// 	uni.showModal({
					// 			// 		title: '警告',
					// 			// 		content: '支付进行中，确定要离开？',
					// 			// 		success: (res) => {
					// 			// 			res.confirm ? finishPayment('cancel') : history.pushState(null, null,
					// 			// 				document.URL);
					// 			// 		}
					// 			// 	});
					// 			// };
					// 			// window.addEventListener('popstate', popStateListener);
					// 			// uni.switchTab({
					// 			// 	url: '/pages/order-list/order-list'
					// 			// });
								
					// 		}, 2000);
					// 	}
					// });
				}
			}).catch(error=>{
				console.log(error)
			})
		}
	};

	// 日期选择相关
	const datePickerPopup = ref(null);
	const showDatePicker = () => {
		datePickerPopup.value.open();
	};

	const onDateConfirm = (data) => {
		checkInDate.value = data.checkInDate;
		checkOutDate.value = data.checkOutDate;
		datePickerPopup.value.close();

		// 更新总价
		// 总价会通过计算属性自动更新
	};
	
	// onUnload(()=>{
	// 	wx.closeWindow()
	// })
</script>

<style lang="scss" scoped>
	.container {
		background-color: #F5F5F5;
		min-height: 100vh;
		position: relative;
	}

	// 内容区域
	.content-scroll {
		padding-bottom: 128rpx;
		height: 100vh;
		box-sizing: border-box;
	}

	// 卡片通用样式
	.card {
		margin: 20rpx 24rpx 0;
		background: #fff;
		border-radius: 16rpx;
		padding: 32rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

		.card-title {
			font-size: 32rpx;
			font-weight: 500;
			color: #333;
			margin-bottom: 24rpx;
		}

		.divider {
			height: 2rpx;
			background: #EEEEEE;
			margin: 24rpx 0;
		}
	}

	// 酒店信息卡片
	.hotel-info-card {
		.hotel-name {
			font-size: 32rpx;
			font-weight: 500;
			color: #333;
			margin-bottom: 12rpx;
		}

		.hotel-address {
			display: flex;
			align-items: center;
			margin-bottom: 24rpx;

			text {
				font-size: 28rpx;
				color: #666;
				margin-left: 8rpx;
			}
		}

		.date-picker {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 96rpx;
			background: #F8F8F8;
			border-radius: 12rpx;
			padding: 0 24rpx;
			margin-bottom: 24rpx;

			.date-info {
				display: flex;
				align-items: center;

				.date-range {
					display: flex;
					align-items: center;

					.date {
						font-size: 28rpx;
						color: #333;
					}

					.separator {
						margin: 0 16rpx;
						color: #999;
					}
				}

				.nights {
					margin-left: 24rpx;
					font-size: 28rpx;
					color: #666;
					padding-left: 24rpx;
					border-left: 2rpx solid #EEEEEE;
				}
			}
		}

		.room-info {
			display: flex;

			.room-image {
				width: 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
				margin-right: 24rpx;
			}

			.room-detail {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.room-name {
					font-size: 32rpx;
					font-weight: 500;
					color: #333;
				}

				.room-tags {
					display: flex;
					flex-wrap: wrap;
					gap: 12rpx;
					margin: 12rpx 0;

					.tag {
						font-size: 24rpx;
						color: #666;
						background: #F5F5F5;
						padding: 4rpx 12rpx;
						border-radius: 4rpx;
					}
				}

				.cancel-rule {
					display: flex;
					align-items: center;

					text {
						font-size: 28rpx;
						color: #FF6000;
						margin-left: 8rpx;
					}
				}
			}
		}
	}

	// 预订详情卡片
	.booking-detail-card {
		.room-count {
			display: flex;
			align-items: center;

			.count-label {
				font-size: 28rpx;
				color: #333;
				margin-right: 24rpx;
			}

			.count-control {
				display: flex;
				align-items: center;

				.count-btn {
					width: 64rpx;
					height: 64rpx;
					border-radius: 32rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					background: #F5F5F5;

					text {
						font-size: 32rpx;
						color: #333;
					}

					&.minus {
						color: #999;
					}
				}

				.count-value {
					width: 80rpx;
					text-align: center;
					font-size: 32rpx;
					color: #333;
				}
			}

			.count-tip {
				flex: 1;
				text-align: right;
				font-size: 24rpx;
				color: #999;
			}
		}

		.contact-info {
			.input-item {
				margin-bottom: 24rpx;

				.input-label {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 16rpx;
					display: block;
				}

				input {
					width: 100%;
					height: 96rpx;
					background: #F8F8F8;
					border-radius: 12rpx;
					padding: 0 24rpx;
					font-size: 28rpx;
					color: #333;
					box-sizing: border-box;
				}

				.remark-input {
					width: 100%;
					height: 160rpx;
					background: #F8F8F8;
					border-radius: 12rpx;
					padding: 24rpx;
					font-size: 28rpx;
					color: #333;
					box-sizing: border-box;
				}

				.placeholder {
					color: #999;
				}
			}
		}
	}

	// 优惠券卡片
	.coupon-card {
		.coupon-selector {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 88rpx;

			.selector-left {
				display: flex;
				align-items: center;

				text {
					font-size: 28rpx;
					color: #333;
					margin-left: 12rpx;
				}
			}

			.selector-right {
				display: flex;
				align-items: center;

				text {
					font-size: 28rpx;
					color: #999;
					margin-right: 12rpx;
				}
			}
		}
	}

	// 底部占位
	.bottom-placeholder {
		height: 40rpx;
	}

	// 底部操作栏
	.bottom-bar {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 128rpx;
		background: #fff;
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 100;

		.price-info {
			flex: 1;
			display: flex;
			align-items: baseline;

			.price-label {
				font-size: 28rpx;
				color: #333;
			}

			.price-symbol {
				font-size: 28rpx;
				color: #FF6000;
				margin-right: 4rpx;
			}

			.price-value {
				font-size: 40rpx;
				font-weight: 600;
				color: #FF6000;
			}
		}

		.submit-btn {
			width: 280rpx;
			height: 88rpx;
			background: #FF6000;
			color: #fff;
			font-size: 32rpx;
			font-weight: 500;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 0;
		}
	}
</style>